package com.example.demo.controller;

import Mapper.UserMapper;
import cn.dev33.satoken.stp.StpUtil;
import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("register")
    public int register(String nickname, String image) {
        List<User> users = userMapper.getUserByName(nickname);
        List<User> imageUsers = userMapper.getUserImages(image);

        if (users.isEmpty() || imageUsers.isEmpty()) {
            int nextId = userMapper.nextId();
            User newUser = new User();
            newUser.setuserid(nextId);
            newUser.setNickname(nickname);
            newUser.setImages(image);
            userMapper.insertUser(newUser);
            StpUtil.login(nextId);
            System.out.println("登录:" + nextId + "号 " + nickname + " 成功");
            return nextId;
        }
        return userMapper.getUserIdById(nickname);
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

}
